package com.group2.operations.controller;

import com.group2.operations.common.api.ApiErrorCode;
import com.group2.operations.common.api.ApiResult;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    @ResponseBody
    public ApiResult unauthorized() {
        return ApiResult.failed(ApiErrorCode.FORBIDDEN);
    }

    @ExceptionHandler
    @ResponseBody
    public ApiResult handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for(FieldError item : fieldErrors) {
            stringBuilder.append(item.getDefaultMessage()).append(" ");
        }
        return ApiResult.failed(stringBuilder.toString());
    }
}
